#include "net.h"
#include <sys/select.h>

#define MAX_SOCKET_FD 1024

int main(int argc, char *argv[])
{
	int fd, newfd, ret, i; 
	fd_set set, tmpset;
	Addr_in clientaddr;
	socklen_t clientlen = sizeof(Addr_in);

	/*检查参数，小于3个 直接退出进程*/
	Argment(argc, argv);
	/*创建已设置监听模式的套接字*/
	fd = CreateSocket(argv);

	FD_ZERO(&set);	//初始化文件描述符
	FD_ZERO(&tmpset);
	FD_SET(fd, &set);
	while(1){
		tmpset = set;
		if(( ret = select(MAX_SOCKET_FD, &tmpset, NULL, NULL, NULL) ) < 0)
			ErrExit("select");
		if( FD_ISSET(fd, &tmpset)){
			/*接收客户端连接，并生成新的文件描述符*/
			if( (newfd = accept(fd, (Addr *)&clientaddr, &clientlen) ) < 0)
				perror("accept");
			printf("[%s:%d]已建立连接\n", 
				inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port));
			FD_SET(newfd, &set);
		}else{
			for(i = fd + 1; i < MAX_SOCKET_FD; i++){
				/*处理客户端数据*/
				if(FD_ISSET(i, &tmpset)){
					if(DataHandle(newfd) <= 0){
						if( (getpeername
							(i, (Addr*)&clientaddr, &clientlen)) < 0)
							ErrExit("getpeername");
						printf("[%s:%d断开连接]\n", 
							inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port));
						FD_CLR(i, &set);
					}
				}
			}
		}
	}
	return 0;
}

